<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use addons\epay\library\Service;
use fast\Http;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index()
    {
        return $this->view->fetch();
//        $this->redirect('/man.php');
    }

    public function getOpenId()
    {
        $userId = input('user_id');
        $code = input('code');
        $returnPage = base64_decode(str_replace('ctkkk', '/', input('currentpage')));

        $appid = 'wx265943340de95fff';
        $appsecret = '8d46882b1d0f26cb104ac5618fce2023';

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code ";

        $res = Http::get($url);

        // 保存用户的openid到数据库
        $resArray = json_decode($res, true);
        // @todo 出错时
        if (isset($resArray['errcode'])) {

        } else {
            $openid = $resArray['openid'];

            $user = \app\admin\model\User::get($userId);
            $user->mp_openid = $openid;
            $user->save();
        }

        // 跳回到原有的页面
        $this->redirect($returnPage);
    }

}
